package com.zhanglijie.improve.aqs.share;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/10/10 0010 21:38
 */
public class SynchronizedSemaphore {
    volatile int state;
    public SynchronizedSemaphore(int state){
        this.state = state;
    }
    public void acquire() throws InterruptedException {
        for(;;){
            synchronized (this){
                if(state>0){
                    this.state -- ;
                    break;
                }
                this.wait();
                //唤醒后看看是否能够传播唤醒
                if(this.state > 0){
                    this.notifyAll();
                }

            }
        }
    }


    public void release(){
        synchronized (this){
            if(++this.state > 0){
                this.notifyAll();
            }
        }
    }
}
